<script setup>
  import { loginAPI } from '@/apis/user'
  import { ref, reactive } from 'vue'
  import { useUserStore } from '@/stores/user'
  import { onLoad } from '@dcloudio/uni-app'
  //上一页的地址
  const redirectURL = ref('')
  const routeType = ref('')
  //获取地址
  onLoad((options) => {
    console.log(options)
    redirectURL.value = options.redirectURL
    routeType.value = options.routeType
  })
  //获取表单实例
  const accountForm = ref()
  // 表单数据
  const formData = reactive({
    account: 'syt123',
    password: '123456',
  })

  // 存储数据到pinia
  const userStore = useUserStore()
  // 定义表单数据验证规则
  const accountRules = reactive({
    account: {
      rules: [
        { required: true, errorMessage: '请输入登录账号' },
        { pattern: '^[a-zA-Z0-9]{6,8}$', errorMessage: '登录账号格式不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入登录密码' },
        { pattern: '^\\d{6}$', errorMessage: '登录密码格式不正确' },
      ],
    },
  })

  const onSumbit = async () => {
    const formData = await accountForm.value.validate()
    const { data, code } = await loginAPI(formData)
    // console.log(data)
    userStore.token = data

    uni[routeType.value]({
      url: redirectURL.value,
    })
    if (!code == 200) return uni.utils.toast('登录失败，请重试！')
  }
</script>

<template>
  <uni-forms
    :rules="accountRules"
    :model="formData"
    class="login-form"
    ref="accountForm"
  >
    <uni-forms-item name="account">
      <input
        type="text"
        placeholder="请输入账号"
        v-model="formData.account"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <input
        type="text"
        placeholder="请输入密码"
        v-model="formData.password"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <button class="submit-button" @click="onSumbit">登录</button>
  </uni-forms>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
